package burubaka.controller.top;

import java.util.ArrayList;
import java.util.List;

import org.slim3.controller.Navigation;
import org.slim3.util.BeanUtil;

import burubaka.bean.HandicappingBean;
import burubaka.common.controller.Controller;
import burubaka.model.Handicapping;
import burubaka.model.RaceInfo;
import burubaka.model.Tipster;
import burubaka.service.HandicappingService;
import burubaka.service.RaceInfoService;
import burubaka.service.TipsterService;

import com.google.appengine.api.datastore.Key;

public class HandicappingListController extends Controller {

	private RaceInfoService raceInfoService = new RaceInfoService();
	private HandicappingService handicappingService = new HandicappingService();
	private TipsterService tipsterService = new TipsterService();

	@Override
	public Navigation init() throws Exception {
		RaceInfo raceInfo = raceInfoService.getCurrentRaceInfo();
		if (raceInfo == null) {
			return forward("handicappingList.jsp");
		}
		List<Handicapping> handicappingList = handicappingService.getHandicappingList(raceInfo.getRaceDate());
		List<HandicappingBean> ret = getHandicappingBeanList(handicappingList);
		requestScope("handicappingList", ret);
		return forward("handicappingList.jsp");
	}

	/**
	 * 前回予想を取得する
	 * 
	 * @return Navigation
	 * @throws Exception
	 */
	public Navigation findLastHandicapping() throws Exception {
		RaceInfo raceInfo = raceInfoService.getLastRaceInfo();
		if (raceInfo == null) {
			return forward("lastRaceRanking.jsp");
		}
		List<Handicapping> handicappingList = handicappingService.getHandicappingListOrderByWithdrawal(raceInfo
				.getRaceDate());
		List<HandicappingBean> ret = getHandicappingBeanList(handicappingList);

		HandicappingBean oldBean = new HandicappingBean();
		int i = 1;
		for (HandicappingBean bean : ret) {
			bean.setOrder(String.valueOf(i));
			if (bean.getWithdrawal() == oldBean.getWithdrawal()) {
				bean.setOrder(oldBean.getOrder());
			}
			oldBean = bean;
			i++;
		}
		requestScope("raceInfo", raceInfo);
		requestScope("lastRaceRankingList", ret);
		return forward("lastRaceRanking.jsp");
	}

	/**
	 * 予想一覧を取得する
	 * 
	 * @param raceInfo
	 * @return 予想一覧
	 */
	private List<HandicappingBean> getHandicappingBeanList(List<Handicapping> handicappingList) {
		List<HandicappingBean> ret = new ArrayList<HandicappingBean>();
		for (Handicapping handicapping : handicappingList) {
			HandicappingBean been = new HandicappingBean();

			Key key = handicapping.getKey().getParent();
			Tipster tipster = tipsterService.findByKey(key);

			BeanUtil.copy(handicapping, been);
			been.setNickName(tipster.getNickname());

			ret.add(been);
		}
		return ret;
	}

}
